import router from './router'
import store from './store'
import storage from 'store'
import NProgress from 'nprogress' // progress bar
import '@/components/NProgress/nprogress.less' // progress bar custom style
import notification from 'ant-design-vue/es/notification'
import { setDocumentTitle, domTitle } from '@/utils/domUtil'
import { getToken, removeToken } from '@/utils/util.js'
import { asyncRouterMap } from '@/config/router.config'
function hasPermission(roles, permissionRoles) {
  if (!permissionRoles) return true
  return roles.indexOf(permissionRoles) >= 0
}


NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['login', '/404', '/403', 'Home','About','Offer', 'Agreement'] // no redirect whitelist
const loginRoutePath = '/user/login'
const idPhotoRoutePath = '/index'
const defaultRoutePath = '/'

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  to.meta && (typeof to.meta.title !== 'undefined' && setDocumentTitle(`${to.meta.title} - ${domTitle}`))
  if (getToken('pssid')) {
    if (to.path === loginRoutePath) {
      next({ path: defaultRoutePath })
      NProgress.done()
    } else {
      // check login user.roles is null
      if (store.getters.nickname == '') {
        store.dispatch('GetInfo2').then(res => {
          console.log(res.data)
          const roles = ['2']
          // 判断是否是认证的用户，是进入首页，不是到认真页面
          store.dispatch('GenerateRoutes', { roles }).then(() => {
            // 根据roles权限生成可访问的路由表,roles值是路由的code,要权限控制由后端传过来
            // 动态添加可访问路由表
            console.log(store.getters.addRouters)
            router.addRoutes(store.getters.addRouters)
            // 请求带有 redirect 重定向时，登录自动重定向到该地址
            // 产品说统一回到首页去，不需要重定向了
            const redirect = decodeURIComponent(from.query.redirect || to.path)
            console.log(to, from, redirect)
            if (to.path === redirect) {
              // set the replace: true so the navigation will not leave a history record
              next({ ...to, replace: true })
            } else {
              // 跳转到目的路由
              next({ path: idPhotoRoutePath })
            }
          })
        }).catch(err => {
          notification.error({
            message: '错误',
            description: '请求用户信息失败，请重试'
          })
          removeToken('pssid')
          next({ path: loginRoutePath, query: { redirect: to.fullPath } })
        })

      } else {
        let asyncRouterMapList = store.getters.allPath
        // if (to.redirectedFrom) {
        //   let redirectedFrom = to.redirectedFrom
        //   // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
        //   if (asyncRouterMapList.indexOf(redirectedFrom) > -1 && to.redirectedFrom != '/') {
        //     let timestamp = Date.parse(new Date());
        //     next({ path: '/403', replace: true, query: { timestamp: timestamp } })
        //   } else {
        //     next()
        //   }
        // } else {
        //   next()
        // }
        next()
      }
    }
  } else {
    console.log(to)
    if (whiteList.includes(to.name)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      // next({ path: loginRoutePath, query: { redirect: to.fullPath } })
      next({ path: loginRoutePath })
      removeToken('pssid')
      NProgress.done()
    }
  }
})



router.afterEach(() => {
  NProgress.done() // finish progress bar
})
